package values.product
{
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;

import values.common.BonusValue;
import values.common.CostValue;
import values.item.building.FactoryBuildingItemValue;

/**
 * ProductValue
 * @author jliang
 *
 */
public class ProductValue extends EventDispatcher
{
	protected var _template:ProductTemplateValue;

	public function get template():ProductTemplateValue
	{
		return _template;
	}

	public function set template(value:ProductTemplateValue):void
	{
		_template = value;
	}
	
	public function get key():String
	{
		return template.key;
	}
	
	public function get time():Number
	{
		return template.time;
	}
	
	public function get cost():CostValue
	{
		return template.cost;
	}
	
	public var bonusFunc:Function;
	
	public function get bonus():BonusValue
	{
		return bonusFunc(this);
	}
	
	public var owner:FactoryBuildingItemValue;
	
	public function get isActived():Boolean
	{
		return owner.checkProductActive(key);
	}
	
	public function get possiblePlus():Number
	{
		var rand:Number = 1 + Math.ceil(100 * Math.random());
		var temp:Array = template.possiblePlus.sortOn("possibility", Array.NUMERIC | Array.DESCENDING);
		
		var acc:Number = 0;
		for (var i:int = 0; i < temp.length; i++)
		{
			var last:Number = (i == 0) ? 100 : (100 - acc);
			var next:Number = last - temp[i].possibility;
			if (next < rand && rand <= last)
			{
				return temp[i].value;
			}
			acc += temp[i].possibility;
		}
		
		return 1;
	}
}
}



